package org.chen.flight.service.task;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.flight.request.FlightSearchRequest;
import org.chen.common.flight.response.OneWayFlightSearchResponse;
import org.chen.common.flight.response.RoundTripFlightSearchResponse;
import org.chen.common.task.ScheduledTaskEntity;
import org.chen.common.task.TaskExecutionLogEntity;
import org.chen.common.email.dto.EmailConfigDTO;
import org.chen.common.flight.*;
import org.chen.common.result.ResultVO;
import org.chen.flight.feign.SystemClient;
import org.chen.common.email.request.EmailNotificationRequest;
import org.chen.flight.mapper.ScheduledTaskMapper;
import org.chen.flight.mapper.TaskExecutionLogMapper;
import org.chen.common.task.ScheduledTask;
import org.chen.common.task.ScheduledTaskRequest;
import org.chen.common.task.TaskExecutionResult;
import org.chen.flight.service.ExcelExportService;
import org.chen.flight.service.flight.FlightSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.io.File;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

/**
 * 重构后的航班定时任务服务
 * 支持动态日期计算和批量执行
 */
@Service
@Slf4j
public class FlightScheduleService implements ApplicationRunner {

    @Autowired
    private TaskScheduler taskScheduler;

    @Autowired
    private FlightSearchService flightSearchService;

    @Autowired
    private ExcelExportService excelExportService;

    @Autowired
    private SystemClient systemConfigService;

    @Autowired
    private ScheduledTaskMapper scheduledTaskMapper;

    @Autowired
    private TaskExecutionLogMapper taskExecutionLogMapper;

    @Autowired
    private ObjectMapper objectMapper;

    // 内存中的调度任务引用
    private final Map<String, ScheduledFuture<?>> scheduledFutures = new ConcurrentHashMap<>();

    /**
     * 系统启动时自动恢复任务
     */
    @Override
    public void run(ApplicationArguments args) {
        log.info("系统启动，开始恢复定时任务...");

        List<ScheduledTaskEntity> activeTasks = scheduledTaskMapper.findActiveTasks();

        for (ScheduledTaskEntity taskEntity : activeTasks) {
            try {
                ScheduledTask task = taskEntity.toScheduledTask();

                if ("ACTIVE".equals(task.getStatus())) {
                    // 重新创建调度任务
                    ScheduledFuture<?> future = taskScheduler.schedule(
                            () -> executeScheduledTask(task.getId()),
                            new CronTrigger(task.getCronExpression())
                    );
                    scheduledFutures.put(task.getId(), future);

                    log.info("恢复活跃任务: {} - {}", task.getName(), task.getCronExpression());
                } else if ("PAUSED".equals(task.getStatus())) {
                    log.info("发现暂停任务: {} - 保持暂停状态", task.getName());
                }

            } catch (Exception e) {
                log.error("恢复任务失败: {}", taskEntity.getName(), e);
            }
        }

        log.info("定时任务恢复完成，共恢复 {} 个任务", scheduledFutures.size());
    }

    /**
     * 系统关闭时停止所有任务
     */
    @PreDestroy
    public void shutdown() {
        log.info("系统关闭，停止所有定时任务...");

        // 取消所有调度任务
        scheduledFutures.values().forEach(future -> {
            if (future != null && !future.isCancelled()) {
                future.cancel(false);
            }
        });
        scheduledFutures.clear();

        // 更新数据库中活跃任务的状态
        scheduledTaskMapper.stopAllActiveTasks();

        log.info("所有定时任务已停止");
    }

    /**
     * 创建动态日期定时任务
     */
    public ScheduledTask createScheduledTask(ScheduledTaskRequest request) {
        ScheduledTask task = new ScheduledTask();

        // 基础信息
        task.setId(UUID.randomUUID().toString());
        task.setName(request.getName());
        task.setCreatedAt(LocalDateTime.now());
        task.setStatus("ACTIVE");

        // 搜索条件
        task.setDeparture(request.getDeparture());
        task.setDestination(request.getDestination());
        task.setTripType(request.getTripType());
        task.setAdults(request.getAdults());
        task.setChildren(request.getChildren());
        task.setInfants(request.getInfants());
        task.setCabinClass(request.getCabinClass());

        // 动态日期配置
        task.setBaseDate(request.getBaseDate());
        task.setCrawlCycle(request.getCrawlCycle());
        task.setExecutionCount(request.getExecutionCount());
        task.setRoundTrip("roundtrip".equals(request.getTripType()));
        task.setRoundTripDays(request.getRoundTripDays());

        // 调度和导出配置
        task.setCronExpression(request.getCronExpression());
        task.setExportPath(request.getExportPath());
        task.setExportLowestPriceOnly(request.isExportLowestPriceOnly());

        // 邮件配置
        task.setEmailNotification(request.isEmailNotification());
        task.setEmailRecipients(request.getEmailRecipients());

        // 初始化统计数据
        task.setTotalRunCount(0);
        task.setSuccessCount(0);
        task.setFailedCount(0);

        try {
            // 保存到数据库
            ScheduledTaskEntity taskEntity = ScheduledTaskEntity.fromScheduledTask(task);
            scheduledTaskMapper.insert(taskEntity);

            // 创建调度任务
            ScheduledFuture<?> future = taskScheduler.schedule(
                    () -> executeScheduledTask(task.getId()),
                    new CronTrigger(request.getCronExpression())
            );
            scheduledFutures.put(task.getId(), future);

            log.info("创建动态日期定时任务: {} - 周期{}天, 执行{}次, Cron: {}",
                    task.getName(), task.getCrawlCycle(), task.getExecutionCount(), task.getCronExpression());

            return task;

        } catch (Exception e) {
            log.error("创建定时任务失败", e);
            throw new RuntimeException("创建定时任务失败: " + e.getMessage());
        }
    }

    /**
     * 执行定时任务 - 支持动态日期计算
     */
    private void executeScheduledTask(String taskId) {
        // 从数据库获取最新的任务信息
        ScheduledTaskEntity taskEntity = scheduledTaskMapper.selectById(taskId);
        if (taskEntity == null) {
            log.warn("任务不存在: {}", taskId);
            return;
        }

        ScheduledTask task = taskEntity.toScheduledTask();

        if (!"ACTIVE".equals(task.getStatus())) {
            log.info("任务不是活跃状态，跳过执行: {} - {}", task.getName(), task.getStatus());
            return;
        }

        long startTime = System.currentTimeMillis();
        TaskExecutionResult result = new TaskExecutionResult();
        result.setTaskId(task.getId());
        result.setTaskName(task.getName());
        result.setExecuteTime(LocalDateTime.now());
        result.setSearchResults(new ArrayList<>());
        result.setExportedFiles(new ArrayList<>());

        try {
            log.info("开始执行动态日期定时任务: {}", task.getName());

            // 获取今天作为基准日期
            LocalDate today = LocalDate.now();

            // 循环执行指定次数
            for (int i = 0; i < task.getExecutionCount(); i++) {
                try {
                    TaskExecutionResult.SearchResult searchResult;
                    if (task.isRoundTrip() && task.getTripType().equals("roundtrip")) {
                        searchResult = executeRoundTripSearch(task, today, i);
                    } else {
                        searchResult = executeOneWaySearch(task, today, i);
                    }
                    result.getSearchResults().add(searchResult);

                    if (searchResult.getExportFileName() != null) {
                        result.getExportedFiles().add(searchResult.getExportFileName());
                    }

                } catch (Exception e) {
                    log.error("执行第{}次搜索失败: {}", i + 1, e.getMessage());
                    TaskExecutionResult.SearchResult errorResult = new TaskExecutionResult.SearchResult();
                    errorResult.setSearchPeriod(String.format("第%d次执行", i + 1));
                    errorResult.setSearchDuration(0);
                    result.getSearchResults().add(errorResult);
                }
            }

            // 更新任务统计
            task.setLastRunAt(LocalDateTime.now());
            task.setTotalRunCount(task.getTotalRunCount() + 1);
            task.setSuccessCount(task.getSuccessCount() + 1);
            task.setLastRunResult("SUCCESS");

            result.setSuccess(true);

            // 生成执行摘要
            String summary = generateExecutionSummary(result);
            task.setLastExecutionSummary(summary);

            // 更新数据库
            updateTaskExecutionStats(task);

        } catch (Exception e) {
            log.error("执行定时任务失败: {}", task.getName(), e);

            task.setLastRunAt(LocalDateTime.now());
            task.setTotalRunCount(task.getTotalRunCount() + 1);
            task.setFailedCount(task.getFailedCount() + 1);
            task.setLastRunResult("FAILED");
            task.setLastErrorMessage(e.getMessage());

            result.setSuccess(false);
            result.setErrorMessage(e.getMessage());

            // 更新数据库
            updateTaskExecutionStats(task);

        } finally {
            result.setTotalDuration(System.currentTimeMillis() - startTime);

            // 保存执行日志
            saveExecutionLog(result);

            // 发送邮件通知
            if (task.isEmailNotification()) {
                sendEmailNotification(task, result);
            }
        }
    }

    /**
     * 更新任务执行统计到数据库
     */
    private void updateTaskExecutionStats(ScheduledTask task) {
        scheduledTaskMapper.updateExecutionStats(
                task.getId(),
                task.getTotalRunCount(),
                task.getSuccessCount(),
                task.getFailedCount(),
                task.getLastRunAt(),
                task.getLastRunResult(),
                task.getLastErrorMessage(),
                task.getLastExecutionSummary()
        );
    }

    /**
     * 保存执行日志到数据库
     */
    private void saveExecutionLog(TaskExecutionResult result) {
        try {
            TaskExecutionLogEntity logEntity = new TaskExecutionLogEntity();
            logEntity.setTaskId(result.getTaskId());
            logEntity.setTaskName(result.getTaskName());
            logEntity.setExecuteTime(result.getExecuteTime());
            logEntity.setSuccess(result.isSuccess());
            logEntity.setErrorMessage(result.getErrorMessage());
            logEntity.setTotalDuration(result.getTotalDuration());
            logEntity.setExecutionSummary(generateExecutionSummary(result));

            // 序列化复杂对象
            logEntity.setSearchResults(objectMapper.writeValueAsString(result.getSearchResults()));
            logEntity.setExportedFiles(objectMapper.writeValueAsString(result.getExportedFiles()));

            taskExecutionLogMapper.insert(logEntity);

        } catch (Exception e) {
            log.error("保存执行日志失败", e);
        }
    }



    /**
     * 执行往返搜索
     */
    private TaskExecutionResult.SearchResult executeRoundTripSearch(ScheduledTask task, LocalDate baseDate, int executionIndex) {
        long searchStartTime = System.currentTimeMillis();
        TaskExecutionResult.SearchResult searchResult = new TaskExecutionResult.SearchResult();
        
        try {
            // 计算这次搜索的日期范围
            LocalDate departDate = baseDate.plusDays((long) executionIndex * task.getCrawlCycle());
            LocalDate returnDate = null;
            
            if (task.isRoundTrip()) {
                returnDate = departDate.plusDays(task.getRoundTripDays());
            }
            
            // 设置搜索结果信息
            searchResult.setDepartDate(departDate.toString());
            searchResult.setReturnDate(returnDate != null ? returnDate.toString() : null);
            searchResult.setSearchPeriod(String.format("第%d次: %s%s", 
                    executionIndex + 1, 
                    departDate.toString(),
                    returnDate != null ? " - " + returnDate.toString() : ""));

            // 构建搜索请求
            FlightSearchRequest searchRequest = buildSearchRequest(task, departDate, returnDate);
            
            log.info("执行第{}次搜索: {} → {}, 出发: {}, 返程: {}", 
                    executionIndex + 1, task.getDeparture(), task.getDestination(), 
                    departDate, returnDate);

            // 执行搜索
            RoundTripFlightSearchResponse response = flightSearchService.searchRoundTripFlights(searchRequest);

            if (response.isSuccess() && response.getFlights() != null) {
                searchResult.setFlightCount(response.getTotalCount());
                
                // 计算最低价格
                BigDecimal lowestPrice = response.getFlights().stream()
                        .map(this::getFlightRoundTripPrice)
                        .filter(Objects::nonNull)
                        .min(BigDecimal::compareTo)
                        .orElse(BigDecimal.ZERO);
                searchResult.setLowestPrice("¥" + lowestPrice.intValue());
                
                // 导出Excel
                if (response.getTotalCount() > 0) {
                    String fileName = exportSearchResultRoundTrip(task, searchRequest, response, executionIndex);
                    searchResult.setExportFileName(fileName);
                }
                
            } else {
                searchResult.setFlightCount(0);
                searchResult.setLowestPrice("无数据");
                log.warn("第{}次搜索无结果: {}", executionIndex + 1, response.getMessage());
            }

        } catch (Exception e) {
            log.error("第{}次搜索失败: {}", executionIndex + 1, e.getMessage());
            throw e;
        } finally {
            searchResult.setSearchDuration(System.currentTimeMillis() - searchStartTime);
        }
        
        return searchResult;
    }

    /**
     * 执行单程搜索
     */
    private TaskExecutionResult.SearchResult executeOneWaySearch(ScheduledTask task, LocalDate baseDate, int executionIndex) {
        long searchStartTime = System.currentTimeMillis();
        TaskExecutionResult.SearchResult searchResult = new TaskExecutionResult.SearchResult();

        try {
            // 计算这次搜索的日期范围
            LocalDate departDate = baseDate.plusDays((long) executionIndex * task.getCrawlCycle());
            LocalDate returnDate = null;

            if (task.isRoundTrip()) {
                returnDate = departDate.plusDays(task.getRoundTripDays());
            }

            // 设置搜索结果信息
            searchResult.setDepartDate(departDate.toString());
            searchResult.setReturnDate(returnDate != null ? returnDate.toString() : null);
            searchResult.setSearchPeriod(String.format("第%d次: %s%s",
                    executionIndex + 1,
                    departDate.toString(),
                    returnDate != null ? " - " + returnDate.toString() : ""));

            // 构建搜索请求
            FlightSearchRequest searchRequest = buildSearchRequest(task, departDate, returnDate);

            log.info("执行第{}次搜索: {} → {}, 出发: {}, 返程: {}",
                    executionIndex + 1, task.getDeparture(), task.getDestination(),
                    departDate, returnDate);

            // 执行搜索
            OneWayFlightSearchResponse response = flightSearchService.searchOneWayFlights(searchRequest);

            if (response.isSuccess() && response.getFlights() != null) {
                searchResult.setFlightCount(response.getTotalCount());

                // 计算最低价格
                BigDecimal lowestPrice = response.getFlights().stream()
                        .map(this::getFlightOneWayPrice)
                        .filter(Objects::nonNull)
                        .min(BigDecimal::compareTo)
                        .orElse(BigDecimal.ZERO);
                searchResult.setLowestPrice("¥" + lowestPrice.intValue());

                // 导出Excel
                if (response.getTotalCount() > 0) {
                    String fileName = exportSearchResultOneyWay(task, searchRequest, response, executionIndex);
                    searchResult.setExportFileName(fileName);
                }

            } else {
                searchResult.setFlightCount(0);
                searchResult.setLowestPrice("无数据");
                log.warn("第{}次搜索无结果: {}", executionIndex + 1, response.getMessage());
            }

        } catch (Exception e) {
            log.error("第{}次搜索失败: {}", executionIndex + 1, e.getMessage());
            throw e;
        } finally {
            searchResult.setSearchDuration(System.currentTimeMillis() - searchStartTime);
        }

        return searchResult;
    }

    /**
     * 构建搜索请求
     */
    private FlightSearchRequest buildSearchRequest(ScheduledTask task, LocalDate departDate, LocalDate returnDate) {
        FlightSearchRequest request = new FlightSearchRequest();
        request.setDeparture(task.getDeparture());
        request.setDestination(task.getDestination());
        request.setTripType(task.getTripType());
        request.setDepartDate(departDate.toString());
        if (returnDate != null) {
            request.setReturnDate(returnDate.toString());
        }
        request.setAdults(task.getAdults());
        request.setChildren(task.getChildren());
        request.setInfants(task.getInfants());

        return request;
    }

    /**
     * 导出往返搜索结果
     */
    private String exportSearchResultRoundTrip(ScheduledTask task, FlightSearchRequest searchRequest,
                                      RoundTripFlightSearchResponse response, int executionIndex) {
        try {
            ByteArrayResource resource = excelExportService.exportRoundTripToExcel(
                    response, searchRequest, task.isExportLowestPriceOnly());

            // 生成文件名
            String filename = String.format("往返机票_%s-%s_%s.xlsx",
                    response.getSearchRequest().getDeparture(),
                    response.getSearchRequest().getDestination(),
                    java.time.LocalDate.now().toString());

            // 确保导出目录存在
            File exportDir = new File(task.getExportPath());
            if (!exportDir.exists()) {
                exportDir.mkdirs();
            }

            String fullPath = Paths.get(task.getExportPath(), filename).toString();
            Files.write(Paths.get(fullPath), resource.getByteArray());

            log.info("第{}次搜索结果已导出: {}", executionIndex + 1, fullPath);
            return fullPath;

        } catch (Exception e) {
            log.error("导出第{}次搜索结果失败: {}", executionIndex + 1, e.getMessage());
            return null;
        }
    }

    /**
     * 导出单程搜索结果
     */
    private String exportSearchResultOneyWay(ScheduledTask task, FlightSearchRequest searchRequest,
                                      OneWayFlightSearchResponse response, int executionIndex) {
        try {
            ByteArrayResource resource = excelExportService.exportOneWayToExcel(
                    response, searchRequest, task.isExportLowestPriceOnly());

            // 生成文件名
            String filename = String.format("单程机票_%s-%s_%s.xlsx",
                    response.getSearchRequest().getDeparture(),
                    response.getSearchRequest().getDestination(),
                    java.time.LocalDate.now().toString());

            // 确保导出目录存在
            File exportDir = new File(task.getExportPath());
            if (!exportDir.exists()) {
                exportDir.mkdirs();
            }

            String fullPath = Paths.get(task.getExportPath(), filename).toString();
            Files.write(Paths.get(fullPath), resource.getByteArray());

            log.info("第{}次搜索结果已导出: {}", executionIndex + 1, fullPath);
            return fullPath;

        } catch (Exception e) {
            log.error("导出第{}次搜索结果失败: {}", executionIndex + 1, e.getMessage());
            return null;
        }
    }

    /**
     * 获取往返航班价格
     */
    private BigDecimal getFlightRoundTripPrice(RoundTripFlightInfo flight) {
        if (flight.getAdultPrice() != null && flight.getAdultTax() != null) {
            return flight.getAdultPrice().add(flight.getAdultTax());
        }
        return flight.getAdultTotalPrice();
    }

    /**
     * 获取往返航班价格
     */
    private BigDecimal getFlightOneWayPrice(OneWayFlightInfo flight) {
        if (flight.getAdultPrice() != null && flight.getAdultTax() != null) {
            return flight.getAdultPrice().add(flight.getAdultTax());
        }
        return flight.getAdultTotalPrice();
    }

    /**
     * 生成执行摘要
     */
    private String generateExecutionSummary(TaskExecutionResult result) {
        int totalFlights = result.getSearchResults().stream()
                .mapToInt(TaskExecutionResult.SearchResult::getFlightCount)
                .sum();
        
        int successfulSearches = (int) result.getSearchResults().stream()
                .filter(sr -> sr.getFlightCount() > 0)
                .count();
        
        return String.format("共执行%d次搜索，成功%d次，找到%d个航班，导出%d个文件", 
                result.getSearchResults().size(), 
                successfulSearches, 
                totalFlights, 
                result.getExportedFiles().size());
    }

    /**
     * 发送邮件通知
     */
    private void sendEmailNotification(ScheduledTask task, TaskExecutionResult result) {
        try {
            ResultVO<EmailConfigDTO> vo = systemConfigService.getEmailConfig();
            EmailConfigDTO emailConfig = vo.getData();
            if (emailConfig.getEnabled()){
                EmailNotificationRequest build = EmailNotificationRequest.builder().task(task).result(result).build();
                Boolean b = systemConfigService.sendEmailNotification(build);
                if (b) {
                    log.info("邮件通知发送成功: {}", task.getName());
                }
            } else {
                log.info("未启用邮件发送功能");
            }
        } catch (Exception e) {
            log.error("发送邮件通知失败: {}", e.getMessage());
        }
    }

    /**
     * 删除定时任务
     */
    public void deleteScheduledTask(String taskId) {
        try {
            // 取消调度任务
            ScheduledFuture<?> future = scheduledFutures.remove(taskId);
            if (future != null) {
                future.cancel(false);
            }

            // 从数据库删除
            scheduledTaskMapper.deleteById(taskId);

            log.info("删除定时任务: {}", taskId);

        } catch (Exception e) {
            log.error("删除定时任务失败: {}", taskId, e);
            throw new RuntimeException("删除定时任务失败: " + e.getMessage());
        }
    }

    /**
     * 暂停/恢复任务
     */
    public void toggleScheduledTask(String taskId, String action) {
        try {
            ScheduledTaskEntity taskEntity = scheduledTaskMapper.selectById(taskId);
            if (taskEntity == null) {
                throw new RuntimeException("任务不存在: " + taskId);
            }

            if ("pause".equals(action)) {
                // 暂停任务
                ScheduledFuture<?> future = scheduledFutures.remove(taskId);
                if (future != null) {
                    future.cancel(false);
                }
                scheduledTaskMapper.updateStatus(taskId, "PAUSED");

            } else if ("resume".equals(action)) {
                // 恢复任务
                ScheduledTask task = taskEntity.toScheduledTask();
                ScheduledFuture<?> future = taskScheduler.schedule(
                        () -> executeScheduledTask(taskId),
                        new CronTrigger(task.getCronExpression())
                );
                scheduledFutures.put(taskId, future);
                scheduledTaskMapper.updateStatus(taskId, "ACTIVE");
            }

        } catch (Exception e) {
            log.error("切换任务状态失败: {} - {}", taskId, action, e);
            throw new RuntimeException("切换任务状态失败: " + e.getMessage());
        }
    }

    /**
     * 立即执行任务
     */
    public void executeScheduledTaskNow(String taskId) {
        // 在新线程中异步执行
        new Thread(() -> executeScheduledTask(taskId)).start();
    }

    /**
     * 获取定时任务列表
     */
    public List<ScheduledTask> getScheduledTasks() {
        List<ScheduledTaskEntity> entities = scheduledTaskMapper.selectList(null);
        return entities.stream()
                .map(ScheduledTaskEntity::toScheduledTask)
                .collect(Collectors.toList());
    }

    /**
     * 获取任务执行日志
     */
    public List<Map<String, Object>> getTaskLogs(String taskId) {
        List<TaskExecutionLogEntity> logs = taskExecutionLogMapper.findByTaskId(taskId, 50);
        return logs.stream().map(log -> {
            Map<String, Object> logMap = new HashMap<>();
            logMap.put("executeTime", log.getExecuteTime());
            logMap.put("result", log.getSuccess() ? "SUCCESS" : "FAILED");
            logMap.put("duration", log.getTotalDuration());
            logMap.put("message", log.getExecutionSummary());
            return logMap;
        }).collect(Collectors.toList());
    }

    /**
     * 根据ID获取定时任务
     */
    public ScheduledTask getScheduledTask(String taskId) {
        try {
            ScheduledTaskEntity taskEntity = scheduledTaskMapper.selectById(taskId);
            if (taskEntity == null) {
                throw new RuntimeException("任务不存在: " + taskId);
            }
            return taskEntity.toScheduledTask();
        } catch (Exception e) {
            log.error("获取定时任务失败: {}", taskId, e);
            throw new RuntimeException("获取定时任务失败: " + e.getMessage());
        }
    }

    /**
     * 更新定时任务
     */
    public ScheduledTask updateScheduledTask(String taskId, ScheduledTaskRequest request) {
        try {
            // 1. 检查任务是否存在
            ScheduledTaskEntity existingEntity = scheduledTaskMapper.selectById(taskId);
            if (existingEntity == null) {
                throw new RuntimeException("任务不存在: " + taskId);
            }

            ScheduledTask existingTask = existingEntity.toScheduledTask();

            // 2. 取消现有的调度任务
            ScheduledFuture<?> existingFuture = scheduledFutures.remove(taskId);
            if (existingFuture != null) {
                existingFuture.cancel(false);
                log.info("取消现有调度任务: {}", existingTask.getName());
            }

            // 3. 更新任务信息
            ScheduledTask updatedTask = new ScheduledTask();

            // 保持不变的字段
            updatedTask.setId(existingTask.getId());
            updatedTask.setCreatedAt(existingTask.getCreatedAt());
            updatedTask.setTotalRunCount(existingTask.getTotalRunCount());
            updatedTask.setSuccessCount(existingTask.getSuccessCount());
            updatedTask.setFailedCount(existingTask.getFailedCount());
            updatedTask.setLastRunAt(existingTask.getLastRunAt());
            updatedTask.setLastRunResult(existingTask.getLastRunResult());
            updatedTask.setLastErrorMessage(existingTask.getLastErrorMessage());
            updatedTask.setLastExecutionSummary(existingTask.getLastExecutionSummary());

            // 可修改的字段
            updatedTask.setName(request.getName());
            updatedTask.setStatus("ACTIVE"); // 更新后重新激活

            // 搜索条件
            updatedTask.setDeparture(request.getDeparture());
            updatedTask.setDestination(request.getDestination());
            updatedTask.setTripType(request.getTripType());
            updatedTask.setAdults(request.getAdults());
            updatedTask.setChildren(request.getChildren());
            updatedTask.setInfants(request.getInfants());
            updatedTask.setCabinClass(request.getCabinClass());

            // 动态日期配置
            updatedTask.setBaseDate(request.getBaseDate());
            updatedTask.setCrawlCycle(request.getCrawlCycle());
            updatedTask.setExecutionCount(request.getExecutionCount());
            updatedTask.setRoundTrip("roundtrip".equals(request.getTripType()));
            updatedTask.setRoundTripDays(request.getRoundTripDays());

            // 调度和导出配置
            updatedTask.setCronExpression(request.getCronExpression());
            updatedTask.setExportPath(request.getExportPath());
            updatedTask.setExportLowestPriceOnly(request.isExportLowestPriceOnly());

            // 邮件配置
            updatedTask.setEmailNotification(request.isEmailNotification());
            updatedTask.setEmailRecipients(request.getEmailRecipients());

            // 4. 保存到数据库
            ScheduledTaskEntity updatedEntity = ScheduledTaskEntity.fromScheduledTask(updatedTask);
            scheduledTaskMapper.updateById(updatedEntity);

            // 5. 重新创建调度任务（如果任务处于活跃状态）
            if ("ACTIVE".equals(updatedTask.getStatus())) {
                ScheduledFuture<?> newFuture = taskScheduler.schedule(
                        () -> executeScheduledTask(taskId),
                        new CronTrigger(request.getCronExpression())
                );
                scheduledFutures.put(taskId, newFuture);
            }

            log.info("更新定时任务成功: {} - 新的Cron: {}",
                    updatedTask.getName(), updatedTask.getCronExpression());

            return updatedTask;

        } catch (Exception e) {
            log.error("更新定时任务失败: {}", taskId, e);
            throw new RuntimeException("更新定时任务失败: " + e.getMessage());
        }
    }
}
